import { Position, Range, TextEditor, window } from 'vscode';
import { config, MessageFormat } from 'vscode-nls';

const localize = config({
	messageFormat: MessageFormat.file
})(__filename);

export default function replace(editor: TextEditor, flag: string, str: string) {
	const doc = editor.document;
	let start: Position = null;
	let stop: Position = null;

	const REGEXP_TOC_START = new RegExp(`/// FEIDAO ${flag} BEGIN`);
	const REGEXP_TOC_STOP = new RegExp(`/// FEIDAO ${flag} END`);
	for (let index = 0; index < doc.lineCount; index++) {
		const lineText = doc.lineAt(index).text;
		if ((start == null) && (lineText.match(REGEXP_TOC_START))) {
			start = new Position(index + 1, 0);
		} else if (lineText.match(REGEXP_TOC_STOP)) {
			stop = new Position(index - 1, 0);
			break;
		}
	}
	if (start === null || stop === null) {
		window.showErrorMessage(`${localize(0)}:[ // FEIDAO ${flag} BEGIN ] 或 [ // FEIDAO ${flag} END ]`);
		return;
	}
	if (start.line > stop.line) {
		window.showErrorMessage(`${localize(1)}`);
		return;
	}
	const rang = new Range(start, stop);
	// const eol = workspace.getConfiguration('files').get<string>('eol');
	const eol = '\n';
	return editor.edit((editor_builder) => {
		editor_builder.replace(rang, `${eol}${str}${eol}`);
		return true;
	});
}
